<?php
/**
 * Created by PhpStorm.
 * User: dy
 * Date: 2019/12/19
 * Time: 10:50
 */
namespace app\common\controller;
use think\App;
use think\exception\HttpResponseException;
use think\facade\Cookie;
use think\Response;

class ApiController extends BaseController
{
    /**
     * @var string $token
     */
    protected $token;
    public function initialize()
    {
        parent::initialize();
        $this->token = $this->request->header('dd-token',$this->request->param('token',Cookie::get('token')));
        if($this->token){
            //TODO 验证token
        }
    }
    protected function success($msg = '',$data = null,int $code = 1,array $header = [])
    {
        $data = [
            'code'=>$code,
            'msg'=>$msg,
            'data'=>$data
        ];
        if(is_array($msg) || is_object($msg)){
            $data['data'] = $msg;
        }
        $header['Access-Control-Allow-Origin']  = '*';
        $header['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Authorization,x-token';
        $header['Access-Control-Allow-Methods'] = 'GET,POST,PATCH,PUT,DELETE,OPTIONS';
        $response = Response::create($data, 'json')->header($header);
        throw new HttpResponseException($response);
    }

    protected function error(string $msg = '',$data = null,int $code = 0,array $header = [])
    {
        $data = [
            'code'=>$code,
            'msg'=>$msg,
            'data'=>$data
        ];
        $header['Access-Control-Allow-Origin']  = '*';
        $header['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Authorization,x-token';
        $header['Access-Control-Allow-Methods'] = 'GET,POST,PATCH,PUT,DELETE,OPTIONS';
        $response = Response::create($data, 'json')->header($header);
        throw new HttpResponseException($response);
    }
}